package com.core.exception;

import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Context;

/**
 * 
 * 
 * @Description: TODO(捕获全局异常,因为有的异常我们捕获不到)
 * 
 * @author gufei 562401002@qq.com
 * 
 * @date 2015年3月17日 上午9:55:25
 */
public class CrashHandler implements UncaughtExceptionHandler {
	private static CrashHandler mCrashHandler;

	private CrashHandlerListener listener;
	public static Context context;
	public static boolean open = false;

	public void setCrashHandlerListener(CrashHandlerListener listener) {
		this.listener = listener;
	}

	public static void instance(Context context) {
		CrashHandler.context = context;
	}

	/**
	 * 同步方法，以免单例多线程环境下出现异常
	 * 
	 * @param open
	 *            捕获异常开关
	 * 
	 * @return
	 */
	public synchronized static CrashHandler getInstance(boolean open) {
		if (mCrashHandler == null) {
			mCrashHandler = new CrashHandler();
			if (open) {
				CrashHandler.open = open;
				Thread.setDefaultUncaughtExceptionHandler(mCrashHandler);
			}
		}
		return mCrashHandler;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		if (listener != null) {
			if (CrashHandler.context != null) {
				listener.tryDo(thread, ex, CrashHandler.context);
			}
		}
	}
}
